package edu.ubbcs.rs.backend.repository.jpa;

import edu.ubbcs.rs.backend.model.User;
import edu.ubbcs.rs.backend.repository.UserRepository;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 * @author Merli Andras-Bertalan
 * @version 1.0
 * @created 09-jan.-2015 15:37:44
 */
@Stateless(name = "UserRepository")
public class JPAUserRepository extends AbstractJPABaseRepository<User, Long> implements UserRepository {

    @PersistenceContext(unitName = "reservation_system_unit")
    private EntityManager em;

    public JPAUserRepository() {
        super(User.class);
    }

    @Override
    public User getUserByUsernameAndPassword(String email, String password) {
        try {
            TypedQuery<User> query = em.createQuery(
                    "SELECT u FROM User u WHERE u.email = :email AND u.password = :password", User.class);
            query.setParameter("email", email);
            query.setParameter("password", password);

            if (query.getResultList().isEmpty()) {
                return null;
            } else {
                return query.getSingleResult();
            }
        } catch (final javax.ejb.TransactionRolledbackLocalException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public User getUserByUsername(String name) {
        try {
            System.out.println("NAME REP: " + name);
            TypedQuery<User> query = em.createQuery(
                    "SELECT u FROM User u WHERE u.name = :name", User.class);
            query.setParameter("name", name.trim());

            if (query.getResultList().isEmpty()) {
                return null;
            } else {
                return query.getSingleResult();
            }
        } catch (final javax.ejb.TransactionRolledbackLocalException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
